package com.ldn.basic.utils.ali;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @author 李大牛家的牛 (scafel@163.com)
 * @createDate 2024/9/30 - 10:22
 * @description ...
 **/
@Slf4j
@Component
public class ALiOssUtil {

    public static void uploadToOss(String accessKeyId, String accessKeySecret, String bucket, String endpoint,String folderName, File file) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, folderName +"/"+ file.getName(), file);
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.info("上传结果:{}", result);
        } catch (OSSException oe) {
            log.error("ALi OSS Exception", oe);
            throw new RuntimeException(oe.getErrorMessage());
        } catch (ClientException ce) {
            log.error("ALi OSS Exception", ce);
            throw new RuntimeException(ce.getMessage());
        } catch (Exception ex){
            log.error("文件上传失败", ex);
            throw new RuntimeException(ex.getMessage());
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
